package com.pt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.common.CommonResult;
import com.pt.entity.ForumSection;
import com.pt.entity.ForumTopic;
import com.pt.entity.ForumReply;
import com.pt.entity.User;
import com.pt.service.ForumService;
import com.pt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Api(tags = "论坛管理")
@RestController
@RequestMapping("/api/forum")
@RequiredArgsConstructor
public class ForumController {
    
    private final ForumService forumService;
    private final UserService userService;
    
    @ApiOperation("获取论坛板块列表")
    @GetMapping("/sections")
    public CommonResult<List<ForumSection>> getSections() {
        List<ForumSection> sections = forumService.getAllSections();
        return CommonResult.success(sections);
    }
    
    @ApiOperation("获取板块主题列表")
    @GetMapping("/sections/{sectionId}/topics")
    public CommonResult<IPage<ForumTopic>> getTopics(
            @ApiParam("板块ID") @PathVariable Integer sectionId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size) {
        
        Page<ForumTopic> pageParam = new Page<>(page, size);
        IPage<ForumTopic> topics = forumService.getTopicsBySection(sectionId, pageParam);
        return CommonResult.success(topics);
    }
    
    @ApiOperation("获取主题详情")
    @GetMapping("/topics/{topicId}")
    public CommonResult<ForumTopic> getTopicDetail(@ApiParam("主题ID") @PathVariable Long topicId) {
        ForumTopic topic = forumService.getTopicById(topicId);
        if (topic == null) {
            return CommonResult.error("主题不存在");
        }
        
        // 增加查看次数
        forumService.increaseViewCount(topicId);
        
        return CommonResult.success(topic);
    }
    
    @ApiOperation("获取主题回复列表")
    @GetMapping("/topics/{topicId}/replies")
    public CommonResult<IPage<ForumReply>> getReplies(
            @ApiParam("主题ID") @PathVariable Long topicId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size) {
        
        Page<ForumReply> pageParam = new Page<>(page, size);
        IPage<ForumReply> replies = forumService.getRepliesByTopic(topicId, pageParam);
        return CommonResult.success(replies);
    }
    
    @ApiOperation("发表新主题")
    @PostMapping("/topics")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<ForumTopic> createTopic(@RequestBody ForumTopic topic, HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        topic.setAuthorId(user.getId());
        topic.setCreatedTime(LocalDateTime.now());
        topic.setIsDeleted(false);
        
        ForumTopic createdTopic = forumService.createTopic(topic);
        return CommonResult.success(createdTopic);
    }
    
    @ApiOperation("回复主题")
    @PostMapping("/topics/{topicId}/replies")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<ForumReply> replyTopic(
            @ApiParam("主题ID") @PathVariable Long topicId,
            @RequestBody ForumReply reply,
            HttpServletRequest request) {
        
        User user = userService.getCurrentUser();
        
        reply.setTopicId(topicId);
        reply.setAuthorId(user.getId());
        reply.setCreatedTime(LocalDateTime.now());
        reply.setIsDeleted(false);
        
        ForumReply createdReply = forumService.createReply(reply);
        return CommonResult.success(createdReply);
    }
    
    @ApiOperation("删除主题")
    @DeleteMapping("/topics/{topicId}")
    @PreAuthorize("hasRole('ADMIN') or @forumService.isTopicAuthor(#topicId, authentication.name)")
    public CommonResult<String> deleteTopic(@ApiParam("主题ID") @PathVariable Long topicId) {
        forumService.deleteTopic(topicId);
        return CommonResult.success("删除成功");
    }
    
    @ApiOperation("删除回复")
    @DeleteMapping("/replies/{replyId}")
    @PreAuthorize("hasRole('ADMIN') or @forumService.isReplyAuthor(#replyId, authentication.name)")
    public CommonResult<String> deleteReply(@ApiParam("回复ID") @PathVariable Long replyId) {
        forumService.deleteReply(replyId);
        return CommonResult.success("删除成功");
    }
    
    @ApiOperation("置顶/取消置顶主题")
    @PutMapping("/topics/{topicId}/sticky")
    @PreAuthorize("hasRole('ADMIN')")
    public CommonResult<String> toggleSticky(@ApiParam("主题ID") @PathVariable Long topicId) {
        forumService.toggleSticky(topicId);
        return CommonResult.success("操作成功");
    }
    
    @ApiOperation("锁定/解锁主题")
    @PutMapping("/topics/{topicId}/lock")
    @PreAuthorize("hasRole('ADMIN')")
    public CommonResult<String> toggleLock(@ApiParam("主题ID") @PathVariable Long topicId) {
        forumService.toggleLock(topicId);
        return CommonResult.success("操作成功");
    }
} 